package com.prawn.ift.datasearch.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.sql.Date;
import javax.persistence.criteria.*;

import com.prawn.ift.datasearch.client.IftCollEquipmentClient;
import com.prawn.ift.datasearch.dao.DataRecordRelaDao;
import com.prawn.ift.datasearch.pojo.CheckItem;
import com.prawn.ift.datasearch.pojo.DataRecord;
import com.prawn.ift.datasearch.pojo.DataRecordWithCheckItem;
import com.prawn.ift_collequipment.pojo.Equipment;
import org.hibernate.annotations.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import util.IdWorker;

import com.prawn.ift.datasearch.dao.DataRecordDao;

/**
 * 服务层
 * 
 * @author Administrator
 *
 */
@Service
public class DataRecordService {

	@Autowired
	private DataRecordDao dataRecordDao;

	@Autowired
	private DataRecordRelaDao recordRelaDao;
	
	@Autowired
	private IdWorker idWorker;

	@Autowired
	private IftCollEquipmentClient iftCollEquipmentClient;


	/**
	 * 查询全部列表
	 * @return
	 */
	public List<DataRecord> findAll() {
		return dataRecordDao.findAll();
	}

	
	/**
	 * 条件查询+分页
	 * @param whereMap
	 * @param page
	 * @param size
	 * @return
	 */
	public Page<DataRecord> findSearch(Map whereMap, int page, int size) {
		Specification<DataRecord> specification = createSpecification(whereMap);
		PageRequest pageRequest =  PageRequest.of(page-1, size);
		return dataRecordDao.findAll(specification, pageRequest);
	}

	
	/**
	 * 条件查询
	 * @param whereMap
	 * @return
	 */
	public List<DataRecord> findSearch(Map whereMap) {
		Specification<DataRecord> specification = createSpecification(whereMap);
		return dataRecordDao.findAll(specification);
	}

	/**
	 * 根据ID查询实体
	 * @param id
	 * @return
	 */
	@Cacheable(key="#id",value = "dataRecord")
	public DataRecord findById(String id) {
		return dataRecordDao.findById(id).get();
	}

	/**
	 * 增加
	 * @param dataRecord
	 */
	public void add(DataRecord dataRecord) {
		dataRecord.setId( idWorker.nextId()+"" );
		dataRecordDao.save(dataRecord);
	}

	/**
	 * 修改
	 * @param dataRecord
	 */
	@CacheEvict(key = "#dataRecord.id",value = "dataRecord")
	public void update(DataRecord dataRecord) {
		dataRecordDao.save(dataRecord);
	}

	/**
	 * 删除
	 * @param id
	 */
	@CacheEvict(key = "#id",value = "dataRecord")
	public void deleteById(String id) {
		dataRecordDao.deleteById(id);
	}

	/**
	 * 动态条件构建
	 * @param searchMap
	 * @return
	 */
	private Specification<DataRecord> createSpecification(Map searchMap) {

		return new Specification<DataRecord>() {

			@Override
			public Predicate toPredicate(Root<DataRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicateList = new ArrayList<Predicate>();
                // 编号
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                	predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%"));
                }
                // 所属设备编号
                if (searchMap.get("equipmentId")!=null && !"".equals(searchMap.get("equipmentId"))) {
                	predicateList.add(cb.like(root.get("equipmentId").as(String.class), "%"+(String)searchMap.get("equipmentId")+"%"));
                }
                // 检测项目ID
                if (searchMap.get("checkItemId")!=null && !"".equals(searchMap.get("checkItemId"))) {
                	predicateList.add(cb.like(root.get("checkItemId").as(String.class), "%"+(String)searchMap.get("checkItemId")+"%"));
                }
                // 警告原因
                if (searchMap.get("warningReason")!=null && !"".equals(searchMap.get("warningReason"))) {
                	predicateList.add(cb.like(root.get("warningReason").as(String.class), "%"+(String)searchMap.get("warningReason")+"%"));
                }
                // 
                if (searchMap.get("delFlag")!=null && !"".equals(searchMap.get("delFlag"))) {
                	predicateList.add(cb.like(root.get("delFlag").as(String.class), "%"+(String)searchMap.get("delFlag")+"%"));
                }
				return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

			}
		};

	}

	/**
	 *
	 * @param page 从1开始
	 * @param rows
	 * @return
	 */
	public Page<DataRecordWithCheckItem> getDataRecordPageAndRelation(int page, int rows) {
		PageRequest pageBean=PageRequest.of(page-1,rows);
		Page<DataRecordWithCheckItem> dataRecordList = recordRelaDao.findAll(pageBean);
		return dataRecordList;
	}

	public Page<DataRecordWithCheckItem> getDataRecordPageAndRelationByVo(int page, int rows, Map<String,Object> dataRecordVo) {
		PageRequest pageBean=PageRequest.of(page-1,rows);
		//upAcquisitionTime-downAcquisitionTime 时间段
		Page<DataRecordWithCheckItem> dataRecordList =recordRelaDao.findAll((Specification<DataRecordWithCheckItem>) (root, criteriaQuery, criteriaBuilder) -> {
			/*Join join =Root.join(Root.getModel().getSingularAttribute("ldUser", SystemUser.class), JoinType.LEFT);
			predicate = cb.equal(join.get("branch"), ldBranch);	*/
				List<Predicate> list=new ArrayList<>();
				Join<DataRecordWithCheckItem,CheckItem> join=root.join(root.getModel().getSingularAttribute("checkItem",CheckItem.class),JoinType.LEFT);
				//join.on(criteriaBuilder.equal(join.get("checkItemId"),join.get("id")));

				if(dataRecordVo.get("upAcquisitionTime")!=null&&dataRecordVo.get("downAcquisitionTime")!=null){
					SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
					try {
						list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("acquisitionTime").as(Date.class),dateFormat.parse((String)dataRecordVo.get("upAcquisitionTime"))));
						list.add(criteriaBuilder.lessThanOrEqualTo(root.get("acquisitionTime").as(Date.class),dateFormat.parse((String)dataRecordVo.get("downAcquisitionTime"))));
					} catch (ParseException e) {
						e.printStackTrace();
					}

				}
				if (dataRecordVo.get("equipmentId")!=null && !"".equals(dataRecordVo.get("equipmentId"))){
					list.add(criteriaBuilder.equal(root.get("equipmentId").as(String.class),dataRecordVo.get("equipmentId")));
				}

				if (dataRecordVo.get("channelNo")!=null && !"".equals(dataRecordVo.get("channelNo"))){
					list.add(criteriaBuilder.equal(root.get("channelNo").as(String.class),dataRecordVo.get("channelNo")));
				}
				if (dataRecordVo.get("checkItemId")!=null && !"".equals(dataRecordVo.get("checkItemId"))){
					list.add(criteriaBuilder.equal(root.get("checkItemId").as(String.class),dataRecordVo.get("checkItemId")));
				}
				if (dataRecordVo.get("isWarning")!=null && !"".equals(dataRecordVo.get("isWarning"))){
					list.add(criteriaBuilder.equal(root.get("isWarning").as(String.class),dataRecordVo.get("isWarning")));
				}
				if (dataRecordVo.get("isRead")!=null && !"".equals(dataRecordVo.get("isRead"))){
					list.add(criteriaBuilder.equal(root.get("isRead").as(String.class),dataRecordVo.get("isRead")));
				}
				if (dataRecordVo.get("isTreatment")!=null && !"".equals(dataRecordVo.get("isTreatment"))){
					list.add(criteriaBuilder.equal(root.get("isTreatment").as(String.class),dataRecordVo.get("isTreatment")));
				}
				return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
			},pageBean);
		return dataRecordList;
	}
}
